package com.yxzx.api.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.yxzx.api.dto.RestStatusCode;
import com.yxzx.api.exception.CustomException;
import com.yxzx.api.util.CaptchaUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.Duration;

@RestController
@RequestMapping("/api/captcha")
@Api("验证码生成和验证")
public class CaptchaController {


    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;



    @GetMapping("/image")
    public void getKaptcha(HttpServletRequest request, HttpServletResponse response,@RequestParam(required = true) String phone) throws IOException {

        response.setDateHeader("Expires",0);
        //禁用浏览器缓存
        response.setHeader("Cache-Control","no-store,no-cache，post-check=0,pre-check=0");

        response.setHeader("Pragma","no-cache");

        //设置返回类型
        response.setContentType("image/jpeg");

        //获取随机验证码
        String capText=defaultKaptcha.createText();

        //加入电话号进行区分
        String key= CaptchaUtil.IMG_CAPTCHA_KEY+phone;
        //放到缓存中
        redisTemplate.boundValueOps(key).set(capText, Duration.ofMinutes(10));


        BufferedImage bi=defaultKaptcha.createImage(capText);

        ServletOutputStream outputStream = response.getOutputStream();

        ImageIO.write(bi,"jpg",outputStream);


        try{
            outputStream.flush();
        }finally {
            outputStream.close();
        }
    }

    @GetMapping("/checkCaptcha")
    public ResponseEntity<String> checkCaptcha(String code,String phone){

        //用手机号生成key，用于从缓存中取得验证码
        String key=CaptchaUtil.IMG_CAPTCHA_KEY+phone;

        //从缓存获取图片验证码
        String cacheKey=redisTemplate.boundValueOps(key).get();

        if(StringUtils.hasText(cacheKey)&& cacheKey.equalsIgnoreCase(code)){
            return  ResponseEntity.ok("验证成功");
        }else{
            throw new CustomException(phone, RestStatusCode.CAPTCHA_IMAGE_ERROR.getCode(),RestStatusCode.CAPTCHA_IMAGE_ERROR.getMessage());
        }
    }

    @GetMapping("/sms")
    public ResponseEntity<String> getSmsCode(String phone){

        String capText=defaultKaptcha.createText();

        String key=CaptchaUtil.SMS_CAPTCHA_KEY+phone;

        redisTemplate.boundValueOps(key).set(capText,Duration.ofMinutes(10));

        //通过短信网关发送到客户手机


        System.out.println("*******************已发送短信到手机"+phone+"的短信为："+capText);

        return ResponseEntity.ok("已发送");
    }

}
